<template>
  <div class="out">
    <div class="kuang">
      <el-form ref="formRef" :model="form" label-width="60px">
        <el-form-item label="用户名:">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码:">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit()">登录</el-button>
          <el-button>注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import axios from '@/services/request'
import { setToken } from '@/plugins/cookies'
import { storeData } from '@/strore'  //pinia

import type { ComponentInternalInstance } from "vue";
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const gp = appContext.config.globalProperties;

const router = useRouter()  // route的调用
const store = storeData() //pinia

// from数据
const form = reactive({
  username: "admin",
  password: "admin",
});

const formRef = ref<any>(null);

// 登录事件
const onSubmit = () => {
  formRef.value?.validate((valid:any) => {
    if (!valid) {
      return false;
    }
    //登录
    axios.post("/admin/login",{
      username:form.username,
      password: form.password
    }).then((res: ResponseData) => {
        console.log("token", res);
        if(res?.msg == 'ok'){
          gp.$message.success('登录成功')
          setToken(res.data.token)
          getUserInfo(res.data.token)
          router.push('/')
        }else{
          gp.$message.success('登录失败')
        }
      })
      .finally(() => {});

    // gp?.$axios({
    //   apiKey: ["login", "login"],
    //   method: "post",
    //   params: {
    //     username: form.username,
    //     password: form.password,
    //   },
    // })
    //   .then((res: ResponseData) => {
    //     console.log("token", res);
    //     if(res?.msg == 'ok'){
    //       setToken(res.data.token)
    //       // gp.$messageNotion({
    //       //   message: '登录成功',
    //       //   type: 'success'
    //       // })
    //       gp.$message.success('登录成功')
    //       router.push('/')
    //     }else{
    //       gp.$message.success('登录失败')
    //     }
    //   })
    //   .finally(() => {});
  });
};

// 获取用户信息
const getUserInfo = (token:string) =>{
  axios.post('admin/getinfo',{
    token:token
  }).then((res)=>{
    console.log('userinfo',res.data);
    store.userinfo = res.data
  })
}
</script>

<style scoped lang="less">
.out {
  width: 100%;
  height: calc(100vh);
  display: flex;
  justify-content: center;
  align-items: center;
}
.kuang {
  height: 300px;
  width: 450px;
  // padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #e3e3e3;
  border-radius: 15px;
}
.kuang:hover {
  box-shadow: 1px 1px 100px #ebeaea;
}
</style>
